package org.sky.security;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class authenticationSuccessHandler implements AuthenticationSuccessHandler {
    private Logger logger = LogManager.getLogger(authenticationSuccessHandler.class.getName());
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String ip = request.getRemoteAddr();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String loginTime = dateFormat.format(new Date());
        String authority = userDetails.getAuthorities().iterator().next().getAuthority();
        logger.trace("ip Address:" + ip + "   Time:" + loginTime + "  User:" + userDetails.getUsername()+" authority:"+authority);
        response.sendRedirect("/index.jsp");
    }

}
